// src/pages/VideoEditor.tsx
import React, { useEffect, useCallback, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import './VideoEditor.css'; // 引入VideoEditor的CSS
import NewHeader from '@/components/NewHeader';
import Timeline from '@/components/timeline/Timeline'; // 引入新的Timeline组件
import VideoPreview from '@/components/VideoPreview';
import '@/components/VideoPreview.css';
import { getTemplateById } from '@/services/project';
import { loadDraft, setDraftId, setScriptData } from '@/store/draftsSlice';
import { clearSelectedSegment } from '@/store/selectedSegmentSlice';
import { message } from 'antd';
import { eventBus } from '@/utils';
import { RootState } from '@/store';
import SegmentFormSwitcher from '@/components/SegmentFormSwitcher';

const VideoEditor: React.FC = () => {
    const dispatch = useDispatch();
    // 从Redux store获取当前草稿ID
    const currentDraftId = useSelector((state: RootState) => state.drafts.draftId);
    // 使用 ref 来跟踪是否已经初始化过
    const isInitialized = useRef(false);

    // 获取草稿的数据
    const fetchDraftData = useCallback(
        async (id: string) => {
            try {
                // 在重新获取草稿数据前清空选中的片段
                dispatch(clearSelectedSegment());
                // 并行调用获取草稿详情和所有素材
                const draftResponse = await getTemplateById(id);
                // 处理草稿详情
                if (!draftResponse) {
                    message.error('获取草稿详情失败！');
                    return;
                }
                // 设置轨道信息
                dispatch(loadDraft(draftResponse.data.draft_info));
                dispatch(setScriptData(draftResponse.data.script_content));
            } catch (err) {
                message.error('获取数据失败！');
            }
        },
        [dispatch]
    );

    // 初始化时从URL获取草稿ID并直接获取对应草稿的详细信息
    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const id = urlParams.get('draftId') || '';
        if (!id) {
            message.warning('该草稿不存在');
            return;
        }

        // 避免重复初始化
        if (isInitialized.current) return;
        isInitialized.current = true;

        // 设置store中DraftId
        dispatch(setDraftId(id));
        // 获取草稿数据
        fetchDraftData(id);
    }, [dispatch, fetchDraftData]);

    // 订阅轨道添加事件，重新获取草稿数据
    useEffect(() => {
        if (!currentDraftId) return;

        // 订阅轨道添加事件
        const unsubscribeTrackAdded = eventBus.on('track:added', () => {
            // 重新获取草稿数据以更新轨道列表
            fetchDraftData(currentDraftId);
        });

        // 订阅轨道删除事件，重新获取草稿数据
        const unsubscribeTrackDeleted = eventBus.on('track:deleted', () => {
            // 重新获取草稿数据以更新轨道列表
            fetchDraftData(currentDraftId);
        });

        // 订阅草稿更新事件，重新获取草稿数据
        const unsubscribeDraftUpdated = eventBus.on('draft:updated', () => {
            // 重新获取草稿数据以更新草稿信息
            fetchDraftData(currentDraftId);
        });
        // 组件卸载时取消订阅
        return () => {
            unsubscribeTrackAdded();
            unsubscribeTrackDeleted();
            unsubscribeDraftUpdated();
        };
    }, [currentDraftId, fetchDraftData]);

    return (
        <div className="editor-container">
            <NewHeader />
            <div className="middle-container">
                <div className="boxes-container">
                    {/* left-box 是盒子宽度 用来放容器 */}
                    {/* 视频预览区 */}
                    <div className="left-box">
                        <VideoPreview />
                    </div>
                    <div className="right-box">
                        <div>
                            {/* 媒体表单切换器 / 属性面板 */}
                            <SegmentFormSwitcher />
                        </div>
                    </div>
                </div>
            </div>
            <div className="bottom-box">
                {/* 底部大盒子，现在由Timeline组件管理 */}
                <Timeline />
            </div>
        </div>
    );
};
export default VideoEditor;
